package com.tjetc;

import org.dom4j.DocumentException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 *
 *
 * @author gaoyongxiang
 * @version v1.0
 * @date 2025/8/20
 */
public class MyExecutor implements Executor {
    // 数据库连接对象
    MyConfiguration configuration = new MyConfiguration();

    @Override
    public <T> T query(String statement, Object... params) throws SQLException, DocumentException, ClassNotFoundException {
        // 获取链接对象
        Connection connection = getConnection();
        // 准备数据连接
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        // 预编译sql
        preparedStatement = connection.prepareStatement(statement);
        preparedStatement.setString(1, params[0].toString());
        // 拿到结果集
        resultSet = preparedStatement.executeQuery();

        // 将结果映射到JavaBean
        // 简化处理 正式的对象是通过反射获取的 做通用化处理了
        Bank bank = new Bank();
        while (resultSet.next()) {
            bank.setId(resultSet.getInt("id"));
            bank.setName(resultSet.getString("name"));
            bank.setMoney(resultSet.getBigDecimal("money"));
        }
        return (T) bank;
    }

    private Connection getConnection() throws SQLException, DocumentException, ClassNotFoundException {
        return configuration.build("my-config.xml");
    }


}